"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : 备升主时，目标备节点网络链路闪断
Create At   : 2021/08/20
@zou_jialiang0505328126
Description :
    1.停止主节点
    2.切换的同时目标备节点网络链路闪断
    3.备升主
Expect      :
    1.成功
    2.成功
    3.成功
History     :
    Modified by @wan005 2022/2/9:修改断言信息
    Modified by wx1115623 2022/6/8:修改wal_sender_timeout参数以规避超时问题
    Modified by wx1115623 2022/12/5:增加等待时间，待故障结束再刷新配置文件
"""

import unittest
import time
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class NetWork(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '---------Opengauss_Reliability_Hardware_Case137:开始执行---------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.sta1_root_node = Node(node='Standby1Root')
        self.sta1_user_node = Node(node='Standby1DbUser')
        self.com = Common()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta1_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.start_time = ''
        self.end_time = ''
        self.hostmsg = self.primary_root_node.sh('hostname;').result()
        self.log.info(f'hostname is {self.hostmsg}')

        result = self.pri_sh.executDbSql('show wal_sender_timeout;')
        self.log.info(f"wal_sender_timeout is {result}")
        self.wal_sender_timeout = result.strip().splitlines()[-2]

        self.log.info("-------------获取网卡名---------------")
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.sta1_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.sta1_user_node.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                self.log.info(self.networkcard)

    def test_main(self):
        self.log.info('-----------修改wal_sender_timeout------------------')
        result = self.pri_sh.executeGsguc('reload',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          'wal_sender_timeout=12s')
        self.assertTrue(result)
        try:
            self.log.info("---------------1.停止主节点-----------------")
            text = '----step1：停止主节点 expect:成功----'
            result = self.pri_sh.stopDbInstance()
            self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, result,
                          '执行失败:' + text)

            self.log.info("--------------2.切换的同时目标备节点网络链路闪断-------------")
            inject_command = f" rNetLink_flash " \
                f"(repeat,duration,interval,dev) " \
                f"values (30,1,1,{self.networkcard})"
            cfe_thread = ComThread(
                self.com.cfe_inject, args=(
                    self.sta1_root_node, inject_command,))
            cfe_thread.setDaemon(True)
            cfe_thread.start()
            self.start_time = time.time()

            self.log.info("--------------3.备升主-------------")
            text = '----step3：备升主 expect:成功----'
            result = self.sta1_sh.executeGsctl(
                'failover', self.constant.FAILOVER_SUCCESS_MSG)
            self.assertTrue(result)

            self.log.info("-------------获取故障结果-------------")
            cfe_thread.join(100)
            result = cfe_thread.get_result()
            self.log.info(result)
            flg1 = self.constant.cfe_inject_netflash_success_msg in result \
                   or 'Determining IP information' in result
            self.assertTrue(flg1, '执行失败' + text)
            self.end_time = time.time()

        finally:
            self.log.info("-------------等待故障结束((1+1)*30+1)-------------")
            time.sleep(61 - (self.end_time - self.start_time))
            result = self.sta1_sh.exec_refresh_conf()
            self.assertTrue(result, '刷新配置文件失败')

    def tearDown(self):
        self.log.info("---------------还原集群------------")
        result_start = self.pri_sh.executeGsctl(
            'start', 'start', '-M standby')
        result_switchover = self.pri_sh.executeGsctl(
            'switchover', self.constant.SWITCHOVER_SUCCESS_MSG)
        self.pri_sh.exec_refresh_conf()
        self.log.info('-----------还原wal_sender_timeout------------------')
        result = self.pri_sh.executeGsguc('reload',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f'wal_sender_timeout='
                                          f'{self.wal_sender_timeout}')
        self.log.info(result)
        self.assertTrue(result_start, '还原集群失败')
        self.assertTrue(result_switchover, '还原集群失败')
        self.assertTrue(result, '还原wal_sender_timeout失败')
        self.log.info('-----Opengauss_Reliability_Hardware_Case137:执行完成-----')
